


<script setup lang="ts">
import "@/assets/scss/common.scss";
//import '@/static/icon/iconfont.css';
import { ref, watch } from "vue";
import { getUserDetail, checkUpdate,checkV } from "@/api/api";
import { imInit, imLogin,restartImAndPage, restartIm , loginOut as imLoginOut } from "@/hooks/imLogin";
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { userData as userDataStore } from "@/store/userData";
import { imStore } from "@/store/imStore";
import { network } from "@/store/network";
import { systemConfig as systemConfigStore } from "@/store/systemConfig";
import { getSelectConfig, loginOut } from "@/api/api";
import { getPosition } from "@/hooks/getPosition";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import {
    getGroupApplicationList,
    getUserProfile,
    handleJumpToChat,
} from "@/hooks/imHooks";


import { getAppVersion, getPlatform } from "@/utils/utils";
import { restore } from '@/utils/iap'
import { config as configStore } from "@/store/config";
import { position as positionStore } from "@/store/position";
import { ver } from "@/store/ver";
import { noNet } from '@/utils/utils'

const VER = ver();
const NETWORK = network();
let verInt:any = null


const config: any = configStore();

const systemInfo: any = systemInfoStore();
const IM_STORE: any = imStore();
const userData: any = userDataStore();
const systemConfig: any = systemConfigStore();
const position = positionStore();

let flag = false;

const hasNet = ref(true);


const gerV = async()=>{
    const res: any = await checkV({}).catch(() => {});

    const {flag, data} = res;
    if(flag!==1){
        return;
    }

    const a = []
    const i = []

    data.forEach((item:any)=>{
        if(item.slimKey==='1'){
            a.push(item.slimValue)
        }
        if(item.slimKey==='2'){
            i.push(item.slimValue)
        }
    })

    let arr = null;

    const platform = uni.getSystemInfoSync().platform;

    if(platform==='ios'){
        arr = i
    }else{
		console.log(a)
        arr = a
    }

    let currentVersion = '1.0.4';


    /*#ifdef APP-PLUS*/
    currentVersion =await getAppVersion() as string
    /*#endif*/

    const f = arr.some(item=>item===currentVersion)

    VER.setVer(f);
    clearInterval(verInt)
    verInt=null




    // setTimeout(()=>{
    //     VER.setVer(false);
    //     clearInterval(verInt)
    //     verInt=null
    // },5000)
}

const GetUserData = async () => {
    if (!userData.id) {
        uni.hideLoading();

        const pages = getCurrentPages();
        if (pages.length) {
            const currenturl = pages[pages.length - 1].route;
            if (currenturl !== "pages/login/login") {
                console.log("reLaunch--------1");
                uni.reLaunch({
                    url: "/pages/login/login",
                    animationType: "fade-in",
                });
            }
        } else {
            uni.redirectTo({
                url: "/pages/login/login",
            });
        }



        return false;
    }

    const detail: any = await getUserDetail({ id: userData.id }).catch(
        (err) => {}
    );
    const { flag, data } = detail;
    if (flag !== 1) {
        uni.hideLoading();
        return;
    }

    uni.setStorageSync('USER_DATA',data);

    const { id, nickName, openid, photo, sex, phone } = data;
    userData.setUserData(data);
    return true;
};

function checkNet() {
    uni.getNetworkType({
        async success(res) {
            if (res.networkType === "none") {
                noNet();
                NETWORK.setNet(false);
                return;
            } else {
                // uni.showLoading({
                //     title: "加载中...",
                // });
                NETWORK.setNet(true);
                hasNet.value = true;
                clearInterval(int);
                int = null;

                if (!isLogin) {
                    isLogin = true;

                    const bool = await GetUserData();

                    if (!bool) {
                        return;
                    }

                    if (userData.phone) {
                        imLogin(userData.id,false);
                    }
                }
            }
        },
        fail() {
            NETWORK.setNet(false);
            hasNet.value = false;
        },
    });
}
let int:any = null;

let isLogin = false;

const getSystemConfig = async () => {
    if (!userData.id) {
        setTimeout(() => {
            getSystemConfig();
        }, 2000);
        return;
    }

    const slimTypes = [
        "slim:group:user:count",
        "slim:user:label",
        "slim:group:activity",
        "pay:type",
        "slim:user:vip",
        "slim:user:vip:test",
    ];
    const res: any = await getSelectConfig({ slimTypes }).catch(() => {
        setTimeout(() => {
            getSystemConfig();
        }, 100);
    });
    const { flag, data } = res;
    if (flag !== 1) {
        setTimeout(() => {
            getSystemConfig();
        }, 100);
        return;
    }
    systemConfig.setConfig("groupCount", data["slim:group:user:count"]);
    systemConfig.setConfig("groupTag", data["slim:user:label"]);
    systemConfig.setConfig("groupActivity", data["slim:group:activity"]);
    systemConfig.setConfig("payType", data["pay:type"]);
    systemConfig.setConfig("userVip", data["slim:user:vip"]);
	//systemConfig.setConfig("userVip", data["slim:user:vip:test"]);

    if(uni.platform==='ios'){
        restore();
    }



    // getGroupCount();
    // getGroupTag();
    // getGroupActivity();
};


// const preloadPage = ()=>{
//     console.log('App preloadPage preloadPage preloadPage')
//     console.log('App preloadPage preloadPage preloadPage')
//     console.log('App preloadPage preloadPage preloadPage')
//     //let preloaded = false;
//         // const pages = getCurrentPages();
//         // const length = pages.length;
//         // pages.forEach((p,index)=>{
//         //     console.log(p.route);
//         //     // if(p.route==='pages/TUIKit/TUIPages/TUIChat/index'){
//         //     //     // 侧滑返回后隐藏webview
//         //     //     preloaded = true;
//         //     // }
//         //     // const wv = pages[index].$getAppWebview();
//         //     // u = wv.getURL();
//         // })
//     const time = new Date().getTime();
//         const preloadPageUrl = `/pages/TUIKit/TUIPages/TUIChat/index`

//         uni.unPreloadPage({url:preloadPageUrl,success:()=>{
//             console.log('unPreloadPage')
//             console.log('unPreloadPage')
//             console.log('unPreloadPage')
//             console.log('unPreloadPage')
//         },});
//         uni.preloadPage({url:preloadPageUrl,success:()=>{
//         },});
//         uni.preloadPageUrl = preloadPageUrl;

// }

const userLoginOut = async () => {
    await imLoginOut();
    const res: any = await loginOut();
    const { flag } = res;
    if (flag === 9000 || flag === 1) {
        userData.clearUserData();
        uni.removeStorageSync("api_token");
        return true;
    }
};

const init = () => {
    inited = true;
    getSystemConfig();
    imInit();
    /*#ifdef APP-PLUS*/
    //pushListening();
    /*#endif*/
};

let inited = false;

watch(
    () => config.agreement,
    (val, oldVal) => {
        if (val && !inited) {
            init();
            int = setInterval(() => {
                checkNet();
            }, 1000);
        }
    }
);
watch(
    () => IM_STORE.quanziTotalUnread,
    (val, oldVal) => {
		if(val && val > 0){
			uni.setTabBarBadge({
			  index: 1,
			  text: val
			})
		}else{
			uni.removeTabBarBadge({index: 1})
		}
		
    }
);
/*
uni.setTabBarBadge({
      index: 1,
      text: IM_STORE.quanziTotalUnread
    })
	*/
// watch(config.agreement,(val)=>{

// })

onLaunch(async () => {
    gerV();
    verInt = setInterval(()=>{
        gerV();
    },1000)

    if(!userData.id){
        console.log("reLaunch---------2");
        uni.redirectTo({
            url: "/pages/login/login",
            animationType: "fade-in",
        });
		
        return;
    }
    
    if (uni.getStorageSync("api_token")) {
       
        init();
        int = setInterval(() => {
            checkNet();
        }, 1000);
		
    } 
});

// const pushListening = () => {
//     if (!uni.TUIOfflinePush) {
//         setTimeout(() => {
//             pushListening();
//         }, 200);
//         return;
//     }

//     uni.TUIOfflinePush.setOfflinePushListener((pushData) => {
//         // 透传 entity 中的内容，不包含推送的 Message
//         const { type, conversationID } = pushData.data.notification.entity;
//         // 跳转到应用内指定界面
//         if (type === "chat" && conversationID) {
//             uni.$emit("quanziToTab1");
//             uni.switchTab({
//                 url: "/pages/quanzi/quanzi",
//             });
//         }
//     });
// };

let nextCheckTime = null;

let updateVisible = false;

const CheckUpdate = async () => {
    /*#ifdef APP-PLUS*/

    // console.log('CheckUpdate')
    // console.log('CheckUpdate')
    // console.log('CheckUpdate')
    // console.log(VER.ver)

    if(VER.ver){
        return;
    }

    if(updateVisible){
        return;
    }

    if(!uni.getStorageSync("api_token")){
        setTimeout(()=>{
            CheckUpdate();
        },1000)
        return;
    }




    const platform = await getPlatform();
    const terminalSysterm = platform === "ios" ? "01" : "02";
    const currentVersion = await getAppVersion();

    const res = await checkUpdate({ terminalSysterm });
    if (res.flag !== 1) {
        return;
    }
    

    const { version, updateType, isHot, url } = res.data;

    if(uni.getStorageSync(`ignore${version}`)){
        return;
    }

    if (currentVersion !== version) {
        uni.setStorageSync(`ignore${version}`, 1);
        updateVisible = true;
        uni.showModal({
            title: `检查到有新的版本${version}`,
            content: "是否更新？",
            showCancel: updateType === "02",
            confirmText: "更新",
            cancelText: "忽略",
            async success({ confirm,cancel }) {
                updateVisible = false;
                if (confirm) {
                    uni.setStorageSync("updatemsg", res.data);
                    await userLoginOut();
                    uni.reLaunch({
                        url: "/pages/login/login?update=true",
                        animationType: "fade-in",
                    });
                }

                if(cancel) {
                    uni.setStorageSync(`ignore${version}`, 1);
                }
            },
        });
    }

    /*#endif*/
};

let timerHide:any = null
let lastHideTime:any = null
let lastHideTimestamp:any = null
onShow(() => {
	console.log("App Show");
	const now = Date.now();
	const elapsedTime = now - lastHideTimestamp;
	let isReset = IM_STORE.isReset
	if(lastHideTimestamp){
		if(elapsedTime < 600000){
			if(isReset){
				IM_STORE.setReceiving(true)
				restartIm();
			}
		}else{
			plus.runtime.restart();
		}
	}
	
	//IM_STORE.setReset(true)
	/*
	if(lastHideTimestamp && isReset){
		
		lastHideTimestamp = null
		if(elapsedTime < 600000){
			restartIm();
		}else{
			plus.runtime.restart();
		}
	}
	*/
	/*
	if(lastHideTimestamp && isReset){
		lastHideTimestamp = null
		restartIm();
	}
	*/
	IM_STORE.setReset(true)
	/*
	//重置隐藏页面函数
	clearTimeout(timerHide);  
	timerHide = null;
	console.log("App Show");
	const now = Date.now();
	const elapsedTime = now - lastHideTimestamp;
	//120000
	//if(elapsedTime >= 30000){
		
		const pages = getCurrentPages()
		const page0 =  pages[0]
		const page0Route =  page0.route
		uni.setStorageSync('quanziInited', "true");
		//console.log("当前位置")
		uni.setStorageSync('switchTabUrl', page0Route);
		if(page0Route == 'pages/quanzi/quanzi'){
			if(pages.length > 1){
				const currentPage = pages[pages.length - 1]
				const currentRoute = currentPage.route
				//uni.setStorageSync('switchTabUrl', currentRoute);
				uni.navigateBack({
					delta:pages.length,
					animationType:'none',
					success:() =>{
						IM_STORE.setReconnection(true)
						restartImAndPage();
					}
				})
			}else{
				restartImAndPage();
			}
	}
	*/
   /*
	IM_STORE?.conversationList?.forEach((item:any) => {
		uni.$TUIKit.callExperimentalAPI('clearMemoryMessage', item.conversationID)
	})
	*/
    if(inited) {
        uni.getSystemInfo({
            success(result) {
                systemInfo.setSystemInfo(result);
            },
        });
        CheckUpdate();
        if (flag) {
            return;
        }
        if (!flag) {
            flag = true;
            getPosition();
            setTimeout(() => {
                flag = false;
            }, 10000);
        }
    }
});
onHide(() => {
    console.log("App Hide");
	if(systemInfo.platform==='ios'){
		uni.closePreviewImage()
	}
	let isReset = IM_STORE.isReset
	if(isReset){
		lastHideTimestamp = Date.now(); // 记录隐藏时的时间戳
		const pages = getCurrentPages()
		const page0 =  pages[0]
		const page0Route =  page0.route
		if(page0Route == 'pages/quanzi/quanzi'){
			if(pages.length > 1){
				uni.navigateBack({
					delta:pages.length,
					animationType:'none',
					success:() =>{
					}
				})
			}
		}
	}
	
	/*
	timerHide = setTimeout(() => {
		
		//lastHideTime = true
	    const pages = getCurrentPages()
		const page0 =  pages[0]
		const page0Route =  page0.route
		//console.log("当前位置")
		//console.log(page0Route)
		uni.setStorageSync('switchTabUrl', page0Route);
		if(page0Route == 'pages/quanzi/quanzi'){
			const currentPage = pages[pages.length - 1]
			const currentRoute = currentPage.route
			uni.setStorageSync('switchTabUrl', currentRoute);
			uni.navigateBack({
				delta:pages.length,
				animationType:'none',
				success:() =>{
					lastHideTime = true
					console.log("隐藏时候页面返回了")
				}
			})
		}
	}, 120000);
	*/
   
   
});
</script>

<style>
/*每个页面公共css */
@import "./assets/iconfont/iconfont.css";
@import "./assets/scss/common.scss";

/* #ifdef APP-PLUS-NVUE */
@import "./tmui/scss/nvue.css";
/* #endif */
/* #ifndef APP-PLUS-NVUE */
@import "./tmui/scss/noNvue.css";
/* #endif */
</style>
